import http from './http'

export const STATUS_LABEL_BY_CODE = { 0: '停用', 1: '正常' }
function invert(obj){ const r={}; Object.keys(obj).forEach(k=>r[obj[k]]=Number(k)); return r }
export const STATUS_CODE_BY_LABEL = invert(STATUS_LABEL_BY_CODE)

function toCode(val, dict){ if(val===undefined||val===null||val==='') return undefined; const n=Number(val); if(!isNaN(n)) return n; return dict[String(val)] }
function normalize(val){ return val===undefined||val===null?val:String(val) }

function deepGet(obj, path){ if(!path) return obj; return path.split('.').filter(Boolean).reduce((a,k)=>a&&a[k]!==undefined?a[k]:undefined,obj) }
function pickFirst(obj, keys){ for(const k of keys){ if(obj[k]!==undefined&&obj[k]!==null) return obj[k] } return undefined }

const API = {
  list: '/depts',
  add: '/depts',
  update: '/depts', // PUT，id在 body
  remove: (id)=>`/depts/${id}`,
  getById: (id)=>`/depts/${id}`,
  listAll: '/depts/list',
  resp: { root:'', listKey:'rows', totalKey:'total' },
  itemMap: {
    id:['id'], name:['name'], status:['status'],
    updatedAt:['update_time','updateTime'], createdAt:['create_time','createTime']
  }
}

function normalizeItem(o){
  return {
    id: pickFirst(o, API.itemMap.id),
    name: pickFirst(o, API.itemMap.name),
    status: STATUS_LABEL_BY_CODE[Number(pickFirst(o, API.itemMap.status))] ?? normalize(pickFirst(o, API.itemMap.status)),
    updatedAt: pickFirst(o, API.itemMap.updatedAt),
    createdAt: pickFirst(o, API.itemMap.createdAt)
  }
}

export async function listDepts(params){
  const req = { page: params?.page, pageSize: params?.pageSize }
  if(params?.name!==undefined) req.name = params.name
  if(params?.status!==undefined) req.status = toCode(params.status, STATUS_CODE_BY_LABEL)
  const raw = await http.get(API.list, { params: req })
  const root = API.resp.root? deepGet(raw, API.resp.root): raw
  let rows=[], total=0
  if(root && typeof root==='object' && Array.isArray(root[API.resp.listKey])){
    rows = root[API.resp.listKey]; total = Number(root[API.resp.totalKey] ?? rows.length) || rows.length
  } else if(Array.isArray(raw)) { rows = raw; total = raw.length }
  return { list: rows.map(normalizeItem), total }
}

export async function addDept(payload){
  const body = { name: payload.name, status: toCode(payload.status, STATUS_CODE_BY_LABEL) }
  return http.post(API.add, body)
}

export async function updateDept(id, payload){
  const body = { id, name: payload.name, status: toCode(payload.status, STATUS_CODE_BY_LABEL) }
  return http.put(API.update, body)
}

export async function removeDept(id){ return http.delete(API.remove(id)) }
export async function getDeptById(id){ const raw = await http.get(API.getById(id)); return normalizeItem(raw) }
export async function listAllDepts(){ const raw = await http.get(API.listAll); const arr = Array.isArray(raw)? raw: (raw?.rows||[]); return arr.map(normalizeItem) }
